/*
 * Copyright (C) 2022 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.xjh.him.fragment.friend;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.xjh.him.R;
import com.xjh.him.fragment.profile.UserProfileFragment;
import com.xjh.him.adapter.FriendAdapter;
import com.xjh.him.core.BaseFragment;
import com.xjh.him.databinding.FragmentFriendBinding;
import com.xjh.him.dto.friend.FriendDTO;
import com.xjh.him.utils.Utils;
import com.xjh.him.utils.XToastUtils;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.core.PageOption;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.textview.badge.Badge;
import com.xuexiang.xui.widget.textview.badge.BadgeView;
import com.xuexiang.xui.widget.textview.supertextview.SuperTextView;

import org.xjh.tool.Checks;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Page(name = "联系人")
public class FriendFragment extends BaseFragment<FragmentFriendBinding> {
    private int friendApplyCount;
    private Map<String, List<FriendDTO>> groupList;
    private FriendAdapter friendAdapter;
    private Badge newFriendBadge;

    @NonNull
    @Override
    protected FragmentFriendBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentFriendBinding.inflate(inflater, container, false);
    }

    @Override
    protected TitleBar initTitle() {
        return null;
    }


    @Override
    public void initViews() {
        //加载新朋友
        initNewFriendBadgeView();

        //加载好友列表
        initFriendList();

        //初始化监听器
        initListeners();
    }

    public void initListeners() {
        binding.menuNewFriend.setOnSuperTextViewClickListener(new SuperTextView.OnSuperTextViewClickListener() {
            @Override
            public void onClick(SuperTextView superTextView) {
                //小红点隐藏
                if (newFriendBadge != null) {
                    newFriendBadge.hide(true);
                }
                PageOption.to(FriendApplyFragment.class)
                        .setNewActivity(true)
                        .open(FriendFragment.this);
            }
        });
    }

    public void initNewFriendBadgeView() {
        if (isAdded()) {
            String countApplyUrl = Utils.getWebServerApiUrl(requireActivity(), getString(R.string.api_friend_apply_count));
            SimpleCallBack<Integer> countCB = new SimpleCallBack<Integer>() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                @Override
                public void onSuccess(Integer count) throws Throwable {
                    friendApplyCount = count;
                    if (friendApplyCount > 0) {
                        binding.menuNewFriend.setRightString("         ");
                        newFriendBadge = new BadgeView(requireActivity())
                                .bindTarget(binding.menuNewFriend.getRightTextView())
                                .setBadgeGravity(Gravity.END | Gravity.CENTER)
                                .setBadgeNumber(friendApplyCount);
                    }
                }

                @Override
                public void onError(ApiException e) {
                    XToastUtils.toast(e.getDisplayMessage());
                }
            };
            Utils.doGet(countApplyUrl, countCB);
        }
    }

    private void initFriendList() {
        String listFriendUrl = Utils.getWebServerApiUrl(requireActivity(), getString(R.string.api_friend_list));
        SimpleCallBack<Map<String, List<FriendDTO>>> listCB = new SimpleCallBack<Map<String, List<FriendDTO>>>() {
            @Override
            public void onSuccess(Map<String, List<FriendDTO>> result) throws Throwable {
                groupList = result;
                if (!Checks.isEmpty(groupList)) {
                    List<String> characterList = new ArrayList<>(groupList.keySet());
                    friendAdapter = new FriendAdapter(requireActivity(), characterList, groupList);
                    binding.elvFriendList.setAdapter(friendAdapter);
                    binding.elvFriendList.setGroupIndicator(null);

                    friendAdapter.setGroupClickListener(groupClickListener);
                    friendAdapter.setChildClickListener(childClickListener);
                }
            }

            @Override
            public void onError(ApiException e) {
                XToastUtils.toast(e.getDisplayMessage());
            }
        };
        Utils.doGet(listFriendUrl, listCB);
    }

    @SuppressLint("StringFormatMatches")
    private ExpandableListView.OnChildClickListener childClickListener = new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            Bundle bundle = new Bundle();
            FriendDTO friendDTO = (FriendDTO) friendAdapter.getChild(groupPosition, childPosition);
            bundle.putSerializable(UserProfileFragment.KEY_FRIEND_DTO, friendDTO);
            PageOption.to(UserProfileFragment.class)
                    .setNewActivity(true)
                    .setBundle(bundle)
                    .open(FriendFragment.this);
            return false;
        }
    };

    private ExpandableListView.OnGroupClickListener groupClickListener = new ExpandableListView.OnGroupClickListener() {
        @Override
        public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
            if (parent.isGroupExpanded(groupPosition)) {
                parent.collapseGroup(groupPosition);
            }else {
                parent.expandGroup(groupPosition);
            }
            return false;
        }
    };
}
